package com.zhugang.week05;

/**
 * @program algorithms
 * @description: search
 * @author: chanzhugang
 * @create: 2022/07/05 15:00
 */
public class Search {

    public static void main(String[] args) {
        Search search = new Search();
        int[] nums = new int[]{-1, 0, 3, 5, 9, 12};
        int index = search.search(nums, 9);
        System.out.println(index);
    }

    /**
     * 704 二分查找
     *
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        // 标准二分
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
}